package com.abaddon.view;

import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.abaddon.model.Place;
import com.abaddon.model.TagManager;
import com.google.android.maps.GeoPoint;

public class EditPlaceView extends Activity {

	private String oldName = null;
	private GeoPoint newPoint;

	private Button categoriesButton;
	private CharSequence[] allCategories;
	private boolean[] selections;	
	private String[] selectedCategories;
	private String selectedCategoriesString;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.editplace);
		
		//Get place info
		Bundle extras = getIntent().getExtras();
		if(extras != null) {
			String event = extras.getString("event");
			TextView title = (TextView)findViewById(R.id.titleTextView);

			//Set up view if old place
			if(event.equals("editPlace")){
				title.setText(R.string.placeEdit);

				oldName = extras.getString("title");
				String snippet = extras.getString("snippet");
				selectedCategories = extras.getStringArray("categories");

				TextView name = (TextView) findViewById(R.id.nameTextView);
				TextView description = (TextView) findViewById(R.id.descriptionTextView);
				name.setText(oldName);
				description.setText(snippet);
			}
			//Set up view if new place
			else if (event.equals("newPlace")){
				title.setText(R.string.placeNew);
				int latitude = extras.getInt("latitude");
				int longitude = extras.getInt("longitude");
				newPoint = new GeoPoint(latitude, longitude);
			}
		}

		//Set up the multi-choice dialog for the categories button
		List<String> allCategoriesStringList = TagManager.getAbaddonDatabase().getAllCategories();
		Collections.sort(allCategoriesStringList);
		Object[] objCategories = allCategoriesStringList.toArray();
		allCategories = new String[objCategories.length];
		for (int i = 0; i<objCategories.length; i++){
			allCategories[i] = objCategories[i].toString();
		}
		selections =  new boolean[allCategories.length];
		if(selectedCategories != null){
			for(int i=0; i<allCategories.length; i++){
				for(int j=0; j<selectedCategories.length; j++){
					if(allCategories[i].equals(selectedCategories[j])){
						selections[i] = true;
					}
				}
			}
		}

		//Assign buttons
		categoriesButton = (Button) findViewById(R.id.setCategories);
		changeButtonText();

		Button saveButton = (Button) findViewById(R.id.saveButton);
		Button deleteButton = (Button) findViewById(R.id.deleteButton);
		Button cancelButton = (Button) findViewById(R.id.cancelButton);

		//When clicking the categories button
		categoriesButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDialog(0);
			}
		});
		
		//When clicking the save button
		saveButton.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v){
				TextView name = (TextView) findViewById(R.id.nameTextView);
				TextView description = (TextView) findViewById(R.id.descriptionTextView);
				String title = name.getText().toString();
				String snippet = description.getText().toString();
				String[] newCategories = selectedCategoriesString.split(", ");
				Place newPlace;
				if(oldName != null){
					Log.e("EDITPLACEVIEW","OldTitle: " + oldName + " newTitle: " + title);
					TagManager.updatePlaceTitle(oldName, title);
					Place oldPlace = TagManager.getPlace(title);
					newPlace = new Place(oldPlace.getPoint(), title, snippet, newCategories);
				} else {
					newPlace = new Place(newPoint, title, snippet, newCategories);
				}

				TagManager.updatePlace(newPlace);
				finish();
			}
		});

		//When clicking the delete button
		deleteButton.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v){
				if(oldName != null){
					TagManager.removePlace(oldName);
				}
				finish();
			}
		});
		
		//When clicking the cancel button
		cancelButton.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v){
				//TagManager.removePlace(oldName);
				finish();
			}
		});
	}

	/**
	 * When menu button is clicked.
	 */
    public boolean onCreateOptionsMenu(Menu menu){
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.editplace_menu, menu);
    	return true;
    }
    
    /**
     * Opens selected view.
     */
    public boolean onOptionsItemSelected(MenuItem item){
    	//Handle item selection
    	switch (item.getItemId()){
   		case R.id.main:
   			finish();
   			return true;
   		case R.id.settings:
   			startActivity(new Intent("com.abaddon.view.SETTINGSVIEW"));
   			finish();
   			return true;
   		case R.id.help:
   			startActivity(new Intent("com.abaddon.view.HELPVIEW"));
   			finish();
   			return true;
   		case R.id.about:
   			startActivity(new Intent("com.abaddon.view.ABOUTVIEW"));
   			finish();
   			return true;
   		default:
   			return super.onOptionsItemSelected(item);
    	}
    }
    
    /**
     * Displays the multi-choice list. 
     */
	@Override
	protected Dialog onCreateDialog(int id) {
		return 
		new AlertDialog.Builder(this)
		.setTitle(R.string.placeCategories)
		.setMultiChoiceItems(allCategories, selections, new DialogInterface.OnMultiChoiceClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which, boolean isChecked) {
				
			}
		})
		.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
			//When clicking OK
			@Override
			public void onClick(DialogInterface dialog, int clicked) {
				switch(clicked) {
				case DialogInterface.BUTTON_POSITIVE:
					changeButtonText();
					break;
				}
			}
		})
		.create();
	}

	/**
	 * Changes the text of the button to display selected categories.
	 */
	protected void changeButtonText() {
		int count = 0;
		for(int i = 0; i < allCategories.length; i++) {
			if(selections[i]){
				count++;
			}
		}
		if(count==0){
			selectedCategoriesString = "No category";
		}
		else {
			selectedCategoriesString = "";
			for(int i = 0; i < allCategories.length; i++) {
				if(selections[i]){
					selectedCategoriesString += allCategories[i];
					count--;
					if(count > 0){
						selectedCategoriesString += ", ";
					}
				}
			}
		}
		categoriesButton.setText(selectedCategoriesString);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}
}
